import urllib.parse
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from sqlalchemy import Column, Integer, String, DateTime, Boolean, func
from config import MySQL

password = MySQL['PASSWORD']
encoded_password = urllib.parse.quote(password)
SQLALCHEMY_DATABASE_URL = f"mysql+pymysql://{MySQL['USER']}:{encoded_password}@{MySQL['IP']}:{MySQL['PORT']}/{MySQL['DB']}?charset=utf8"

engine = create_engine(SQLALCHEMY_DATABASE_URL, pool_pre_ping=True, pool_recycle=3600)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)


def get_db():
    mysql_db = SessionLocal()
    try:
        yield mysql_db
    finally:
        mysql_db.close()


Base = declarative_base()


class BaseModel(Base):
    __abstract__ = True

    id = Column(Integer, primary_key=True, autoincrement=True)

    username = Column(String(64))
    user_id = Column(String(32))
    c_time = Column(DateTime, server_default=func.now())
    m_time = Column(DateTime, server_default=func.now())
    deleted = Column(Boolean, default=False)
